package cn.edu.swu.miniwebsvr.core;

import cn.edu.swu.miniwebsvr.handler.DefaultHandler;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

public class Router {

    public void route(Parameter request, OutputStream response) {
        Config config = Config.getInstance();
        String requestUrl = request.getUrl();
        // TODO: [222024321072052/然娜·吐尔逊汗] 根据请求的URL获取Handler
        // 1. 根据URL获取匹配的Handler
        Handler handler = config.getHandler(requestUrl);

        // 2. 无匹配Handler → 用DefaultHandler（处理静态资源或404）
        if (handler == null) {
            handler = config.getHandler("/"); // Config中已注册"/"对应DefaultHandler
        }

        // 3. 执行Handler的业务逻辑（若Handler仍为null，返回500）
        if (handler != null) {
            handler.handle(request, response);
        } else {
            // TODO: 极端情况（DefaultHandler未注册），返回500错误
            try {
                PrintWriter writer = new PrintWriter(response, true, StandardCharsets.UTF_8);
                String content = "<h1>500 Internal Server Error</h1><p>Default Handler not found</p>";
                writer.println("HTTP/1.1 500 Internal Server Error");
                writer.println("Content-Type: text/html; charset=UTF-8");
                writer.println("Content-Length: " + content.getBytes(StandardCharsets.UTF_8).length);
                writer.println("Connection: close");
                writer.println();
                writer.println(content);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}